/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 *
 * @author new
 */
public class FileHandler {

    public BufferedReader openReadFile(String fileName) throws FileNotFoundException{

        File inFile = new File(fileName);
        if(!inFile.exists()){
            System.err.println("File not exists.");
        }
        BufferedReader br = new BufferedReader(new FileReader(inFile));
        
        return br;
    }

    public int closeReadFile(BufferedReader br) throws IOException{
        br.close();
        return 0;
    }

    public BufferedWriter openWriteFile(String fileName) throws IOException{

        File outFile = new File(fileName);
        BufferedWriter bw = new BufferedWriter(new FileWriter(outFile));

        return bw;
    }

    public int closeWriteFile(BufferedWriter bw) throws IOException{
        bw.close();
        return 0;
    }

    public int replaceFile(String fileName, String oldFileName){
        
        File oldFile = new File(oldFileName);
        oldFile.delete();
        File newFile = new File(fileName);
        newFile.renameTo(oldFile);

        return 0;
    }

    public void compose(String firstFile, String SecondFile) throws FileNotFoundException, IOException {
        String temp = "ComposeTemp";
        FileHandler fh = new FileHandler();
        BufferedReader br = fh.openReadFile(firstFile);
        BufferedWriter bw = fh.openWriteFile(temp);
        String tempStr = br.readLine();
        while(tempStr != null){
            bw.append(tempStr);
            bw.newLine();
            tempStr = br.readLine();
        }
        fh.closeReadFile(br);
        br = fh.openReadFile(SecondFile);
        tempStr = br.readLine();
        while(tempStr != null){
            bw.append(tempStr);
            bw.newLine();
            tempStr = br.readLine();
        }
        fh.closeReadFile(br);
        fh.closeWriteFile(bw);
        System.gc();
        fh.replaceFile(temp, firstFile);
    }
}
